<?php

/*
right_model.php:负责用户权限控制功能，包括：
*/

class Right_model extends CI_Model
{

	function __construct()
	{
		parent::__construct();
		//载入库文件
		$this->load->library('test_database');
		$this->test_database->test();
		//载入核心类
		$this->load->database($this->test_database->get_db());
	}

	//查询现有权限，格式化数组
	public function getRights()
	{
		$rigths = array();
		$this->db->order_by("right_fun_id", "ASC");
		$query = $this->db->get_where('rights');
		foreach ($query->result() as $v) {
			$rights[$v->right_fun_id] = array($v->right_id, $v->right_fun_name);
		}
		return $rights;
	}

	//分析提交的权限，如果是非法提交，返回FALSE
	public function analyseRights()
	{
		$o_rids = array();
		foreach ($this->getRights() as $k=>$v)
		{
			$o_rids[] = $k;
		}
		array_shift($o_rids);
		$s_rids = $this->input->post('right_ids');
		if (is_array($s_rids)) {
			$arr = array_diff($o_rids, $s_rids);
			if ( empty($arr) )
			{
				return array('1');
			}
			foreach ($s_rids as $id)
			{
				if ('00' == substr($id, 1))
				{
					$id_ = substr($id, 0, 1);
					$e = false;
					foreach ($s_rids as $_id)
					{
						if ('00' != substr($_id, 1) )
						{
							if ((substr($_id,0,1) == $id_))
							{
								$e = true;
							}
						}
					}
					if (!$e) return false;
				}
			}
		}
		return true;
	}

	public function accessCtrl($rid, $urids)
	{
		/***
		rid[string]: 控制器权限
		urids[string]: 
		***/
		$urids = explode('|', $urids);
		$ridr = substr($rid, 0, 1) . '00';
		//查找根权限
		if (in_array($ridr, $urids))
		{
			//查找控制器权限
			if (in_array($rid, $urids))
			{
				return true;
			}
			//查找管理员权限
			elseif (in_array('1', $urids))
			{
				return true;
			}
			//查找超级管理员权限
			elseif (in_array('0', $urids))
			{
				return true;
			}
		}
		return false;
	}

	//检查用户权限有效性
	public function checkRights($right_ids)
	{
		//如果权限是字符串形式，转化成数组
		if (!is_array($right_ids)) {
			$right_ids = explode('|', $right_ids);
		}
		foreach ($right_ids as $id) {
			$query = $this->db->get_where('rights', array('right_fun_id'=>$id), 1);
			if (0 == $query->num_rows()) {
				return false;
			}
		}
		return true;
	}

}